import React, { useState, useEffect, memo, useCallback } from 'react'

const TodoItem = memo(({ data, handleDelete, handleToggle }) => {
    // console.log('item')
    return (
        <li>
            <input checked={data.completed} type='checkbox' onChange={() => handleToggle(data.id)} />
            {data.title}
            <button onClick={() => handleDelete(data)}>删除</button>
        </li>
    )
})

const Todolist = () => {
    const localTodos = localStorage.getItem('todo');
    const [value, setValue] = useState('');
    const [list, setList] = useState(localTodos ? JSON.parse(localTodos) : []);
    const handleChange = (e) => {
        setValue(e.target.value);
    }
    const add = () => {
        setList([...list, { title: value, id: Date.now(), completed: false }]);
    }
    const handleDelete = useCallback((item) => {
        setList((prevList) => prevList.filter(i => i.id !== item.id));
    }, [])
    const handleToggle = useCallback((id) => {
        setList(prevList =>
            prevList.map(todo =>
                todo.id === id ? { ...todo, completed: !todo.completed } : todo
            )
        );
    }, []);
    useEffect(() => {
        localStorage.setItem('todo', JSON.stringify(list));
    }, [list])
    return (
        <div>
            <h1><i>实现todolist功能，封装Todolist组件和TodoItem组件，实现添加、删除、切换、本地存储等功能，尽可能使性能最优，输入框使用受控组件。</i></h1>
            <h1>Todolist-共有{list.length}条</h1>
            <header>
                <input
                    value={value}
                    onChange={handleChange}
                />
                <button onClick={add}>添加</button>
            </header>
            <ul>
                {
                    list.map(item => {
                        return <TodoItem handleToggle={handleToggle} handleDelete={handleDelete} key={item.id} data={item} />
                    })
                }
            </ul>
        </div>
    )
}

export default Todolist;